/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

#import "AppDelegate.h"

#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <React/RCTLinkingManager.h>
#import <HyphenateLite/HyphenateLite.h>
#import <React/RCTPushNotificationManager.h>
#import <EaseUI.h>
#import <AlipaySDK/AlipaySDK.h>
#import "CustomerNavigationController.h"

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  NSURL *jsCodeLocation;
  NSDictionary *notificationMessage;
  
#ifdef DEBUG
  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
  jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
  
  //AppKey:注册的AppKey，详细见下面注释。
  //apnsCertName:推送证书名（不需要加后缀），详细见下面注释。
  EMOptions *options = [EMOptions optionsWithAppkey:@"zuihuiyou#zuihuiyou"];
  options.apnsCertName = @"APN-PROD-J";
  [[EMClient sharedClient] initializeSDKWithOptions:options];
  [[EMClient sharedClient] pushOptions].displayStyle = EMPushDisplayStyleMessageSummary;// 显示消息内容
  
  [[EaseSDKHelper shareHelper] hyphenateApplication:application
                      didFinishLaunchingWithOptions:launchOptions
                                             appkey:@"zuihuiyou#zuihuiyou"
                                       apnsCertName:@"APN-PROD-J"
                                        otherConfig:@{kSDKConfigEnableConsoleLogger:[NSNumber numberWithBool:YES]}];
  //iOS10 注册APNs
  if (NSClassFromString(@"UNUserNotificationCenter")) {
    [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError *error) {
      if (granted) {
#if !TARGET_IPHONE_SIMULATOR
        [application registerForRemoteNotifications];
#endif
      }
    }];
    //return YES;
  }
  
  if([application respondsToSelector:@selector(registerUserNotificationSettings:)])
  {
    UIUserNotificationType notificationTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:nil];
    [application registerUserNotificationSettings:settings];
  }
  
#if !TARGET_IPHONE_SIMULATOR
  if ([application respondsToSelector:@selector(registerForRemoteNotifications)]) {
    [application registerForRemoteNotifications];
  }else{
    UIRemoteNotificationType notificationTypes = UIRemoteNotificationTypeBadge |
    UIRemoteNotificationTypeSound |
    UIRemoteNotificationTypeAlert;
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:notificationTypes];
  }
#endif

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"app"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];
  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  self.window.backgroundColor = [UIColor whiteColor];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  
  self.navigation = [[CustomerNavigationController alloc] init];
  self.navigation.navigationBar.backgroundColor = [UIColor whiteColor];
  [self.navigation pushViewController:rootView.reactViewController animated:YES];
  [self.window addSubview:self.navigation.view];
  
  [self.navigation setNavigationBarHidden:YES];
  [self.window setRootViewController:self.navigation];
  
  [self.window makeKeyAndVisible];
  [NSThread sleepForTimeInterval:2.0];//设置启动页面时间
  //wyz
  [self reachability];
  return YES;
}

// APP进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application
{
  [[EMClient sharedClient] applicationDidEnterBackground:application];
}

// APP将要从后台返回
- (void)applicationWillEnterForeground:(UIApplication *)application
{
  [[EMClient sharedClient] applicationWillEnterForeground:application];
}

// 将得到的deviceToken传给SDK
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
  [[EMClient sharedClient] bindDeviceToken:deviceToken];
  [RCTPushNotificationManager didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
  
  // re-post ( broadcast )
  NSString* token = [[[[deviceToken description]
                       stringByReplacingOccurrencesOfString:@"<" withString:@""]
                      stringByReplacingOccurrencesOfString:@">" withString:@""]
                     stringByReplacingOccurrencesOfString:@" " withString:@""];
  
  [[NSNotificationCenter defaultCenter] postNotificationName:@"ZuihuiyouRemoteNotification" object:token];
}

// 注册deviceToken失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
  NSLog(@"error -- %@",error);
  [RCTPushNotificationManager didFailToRegisterForRemoteNotificationsWithError:error];
}

// Required to register for notifications
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
  [RCTPushNotificationManager didRegisterUserNotificationSettings:notificationSettings];
}

// Required for the notification event.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification
{
  /*NSError *parseError = nil;
  NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:notification
                                                      options:NSJSONWritingPrettyPrinted error:&parseError];
  NSString *str =  [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"apns.content", @"Apns content")
                                                  message:str
                                                 delegate:nil
                                        cancelButtonTitle:NSLocalizedString(@"ok", @"OK")
                                        otherButtonTitles:nil];
  [alert show];*/
  [RCTPushNotificationManager didReceiveRemoteNotification:notification];
}
// Required for the localNotification event.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
  [RCTPushNotificationManager didReceiveLocalNotification:notification];
}

//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
  NSDictionary * userInfo = notification.request.content.userInfo;
  if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    //应用处于前台时的远程推送接受
    //必须加这句代码
    
  }else{
    //应用处于前台时的本地推送接受
  }
  
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
  NSDictionary * userInfo = response.notification.request.content.userInfo;
  if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    //应用处于后台时的远程推送接受
    //必须加这句代码
    
  }else{
    //应用处于后台时的本地推送接受
  }
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
  return [RCTLinkingManager application:application openURL:url
                      sourceApplication:sourceApplication annotation:annotation];
}


#pragma MARK Reachability
- (void)reachability {
  
  Reachability* reach = [Reachability reachabilityWithHostname:@"www.apple.com"];
  // Set the blocks
  reach.reachableBlock = ^(Reachability*reach){
   NSLog(@"REACHABLE!");
  };
  reach.unreachableBlock = ^(Reachability*reach){
    NSLog(@"UNREACHABLE!");
    [self showAlert];
  };
  _reachability = reach;
  [reach startNotifier];
}
- (void)showAlert {
  UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的网络断开了,请连接!" preferredStyle:UIAlertControllerStyleAlert];
  UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"忽略" style:UIAlertActionStyleCancel handler:nil];
  UIAlertAction *setAction = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    
    CGFloat systemVersion = [[UIDevice currentDevice].systemVersion floatValue];
    if (systemVersion < 10) {
      [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"App-Prefs:root=Privacy&path=LOCATION"]];
    }else{
      [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"App-Prefs:root=Privacy&path=LOCATION"]
                                        options:[NSDictionary dictionary]
                              completionHandler:nil];
    }
  }];
  [alert addAction:cancelAction];
  [alert addAction:setAction];
  [self.navigation presentViewController:alert animated:YES completion:nil];
}
//#ifdef IOS9
//- (BOOL)application:(UIApplication *)application
//            openURL:(NSURL *)url
//  sourceApplication:(NSString *)sourceApplication
//         annotation:(id)annotation {
//
//  if ([url.host isEqualToString:@"safepay"]) {
//    //跳转支付宝钱包进行支付，处理支付结果
//    [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//      NSLog(@"result = %@",resultDic);
//    }];
//  }
//
//  return YES;
//}
//#else
//- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
//{
//  if ([url.host isEqualToString:@"safepay"]) {
//    //跳转支付宝钱包进行支付，处理支付结果
//    [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//      NSLog(@"result = %@",resultDic);
//    }];
//  }
//  return YES;
//}
//#endif

@end
